<template>
  <div class="service-container" v-show="goTopShow" @click="goTop">
    <img src="../images/to_top.png" class="service-pic"/>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        scrollTop: "",
        goTopShow: false
      };
    },
    watch: {
      scrollTop(val) {
        if (this.scrollTop > 500) {
          this.goTopShow = true;
        } else {
          this.goTopShow = false;
        }
      }
    },
    methods: {
      handleScroll() {
        this.scrollTop =
          window.pageYOffset ||
          document.documentElement.scrollTop ||
          document.body.scrollTop;
        if (this.scrollTop > 500) {
          this.goTopShow = true;
        }
      },
      goTop() {
        let timer = null,
          _that = this;
        cancelAnimationFrame(timer);
        timer = requestAnimationFrame(function fn() {
          if (_that.scrollTop > 0) {
            _that.scrollTop -= 50;
            document.body.scrollTop = document.documentElement.scrollTop =
              _that.scrollTop;
            timer = requestAnimationFrame(fn);
          } else {
            cancelAnimationFrame(timer);
            _that.goTopShow = false;
          }
        });
      }
    },
    mounted() {
      window.addEventListener("scroll", this.handleScroll);
    },
    destroyed() {
      window.removeEventListener("scroll", this.handleScroll);
    }
  }
</script>

<style lang="less" scoped>
  .service-container {
    position: fixed;
    bottom: 40px;
    right: 20px;
    z-index: 100;
    .service-pic {
      width: 72px;
      height: 72px;
    }
  }
</style>
